/*
 * @(#)ManageService.java $version 2013. 5. 29.
 *
 */

package com.pace.gonu.manage;

import java.util.Calendar;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.pace.gonu.constants.EndType;
import com.pace.gonu.constants.Order;
import com.pace.gonu.model.chnl.PlayChannel;
import com.pace.gonu.play.PlayService;

/**
 * @author pace
 */
@Service
public class ManageService {
	@Autowired
	private PlayService playService;

	public void init() {
		List<PlayChannel> playChannels = playService.getChannels();
		Calendar now = Calendar.getInstance();
		now.add(Calendar.MINUTE, -2);
		for (PlayChannel playChannel : playChannels) {
			initChannel(now, playChannel);
		}
	}

	private void initChannel(Calendar now, PlayChannel playChannel) {
		Calendar lastAccessDate = playChannel.getLastAccessDate();

		if (lastAccessDate != null && now.after(lastAccessDate)) {
			lastAccessDate.getTime();
			if (playChannel.getWinner() != null) {
				playService.initChannel(playChannel.getChnlNumber());
			} else {
				Order winner = Order.otherOrder(Order.valueOf(playChannel.getPlayStatusObject().getOrder()));
				playService.setEndGame(playChannel.getChnlNumber(), winner, EndType.TIMEOUT);
			}
		}
	}

}
